package com.x.erp.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.x.erp.model.Car;
import com.x.erp.model.CarLog;
import com.x.erp.rpc.CarRpcService;
import com.x.erp.util.ConstantState;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 车辆审核信息
 */
@RestController
@RequestMapping("/carRevocation")
public class CarRevocationController extends BaseController {

	@Reference
	private CarRpcService carRpcService;//车辆信息服务

	/**
	 * 入库撤销
	 * @param car
	 * @return
	 */
	@RequestMapping(value = "/carRevocationStock", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel carRevocationSale(Car car, HttpServletRequest request) {
		if(car == null || StringUtils.isEmpty(car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		if(StringUtils.isEmpty(car.getUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "操作人ID不能为空！");
		}
		Car carInfo = new Car();
		carInfo.setCarId(car.getCarId());
		Car selectCar = carRpcService.selectCar(carInfo);
		if (selectCar == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID错误或此车不存在!");
		}
		if (selectCar.getCarStockState() != null && selectCar.getCarStockState() != ConstantState.CAR_STOCK_STATE_IN_ING){
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆已审核，撤销失败!");
		}
		String source = request.getHeader("source");
		List<CarLog> carLogs = new ArrayList<>();
		CarLog carLog = new CarLog(new Date(), car.getUserId(), car.getCarId(), "carStockState", ConstantState.CAR_STOCK_STATE_IN_REVOCATION);
		carLog.setCarLogSource(source);
		carLog.setCarLogInfo("撤销入库申请");
		carLogs.add(carLog);
		carInfo.setCarLogs(carLogs);
		carInfo.setCarStockState(ConstantState.CAR_STOCK_STATE_IN_REVOCATION);
		carInfo.setCarStockTime(this.getDate(0));
		carRpcService.updateCarState(carInfo);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功！", carInfo);
	}
}
